/**
 * Created by levy on 2017/6/1
 */
import React from 'react'
import {getToken, setToken, setUserId} from '../utils/token'
import {Modal, InputItem} from 'antd-mobile'
import request from '../utils/request'


/**
 * props
 *   cb
 */
export default class Login extends React.Component {
  state = {
    hasLogin: !!getToken(),
    username: '',
    password: ''
  }
  render() {
    let {hasLogin} = this.state

    return (
       hasLogin ? null :
        <div className="login">
          <Modal
            title="登录"
            transparent
            maskClosable={false}
            visible={!hasLogin}
            footer={[{ text: '确定', onPress: this.onClose }]}
          >
            <InputItem type="text" placeholder="" clear onChange={this.onInputChange.bind(this, 'username')}>账号</InputItem>
            <InputItem type="password" placeholder="" clear onChange={this.onInputChange.bind(this, 'password')}>密码</InputItem>
          </Modal>
        </div>
    )
  }
  onInputChange (field, value) {
    this.setState({[field]: value})
  }
  onClose = () => {
    let {username, password} = this.state,
      {cb} = this.props

    if(username==''||password==''){
      alert("请随意输入用户名密码");
      return;
    } 

    let body = {
        "username":username,
        "password":password
      }

    request('seckill-login', {
      method: 'POST',
      data: JSON.stringify(body)
    }).then(result => {
      let token = result.data.token
      if (!token) {
        alert('登录失败 请重试!')
        return
      }
      setToken(token)
      setUserId(result.data.userId)
      
      cb && cb()

      this.setState({hasLogin: true})
    })
  }
}
